package neichuan.server.browser;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import neichuan.AttributeKeys;
import neichuan.WorkSpace;
import neichuan.center.ExchangeCenter;
import neichuan.center.RegistCenter;
import neichuan.message.Message;
import neichuan.message.MessageType;
import neichuan.util.log.Log;
import org.apache.log4j.Logger;

import java.net.InetSocketAddress;

public class BrowserServerHandler extends ChannelInboundHandlerAdapter {


    ExchangeCenter exchangeCenter;
    String remoteAddress;
    Channel clientChannel;
    int port;


    /**
     * 接收到浏览器的请求，通知客户端建立临时连接
     * @param ctx
     * @throws Exception
     */
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        //取消读事件
        ctx.channel().config().setAutoRead(false);

        remoteAddress = ctx.channel().remoteAddress().toString();
        if(Log.isDebugEnabled()){
            Log.debug("接收到来自浏览器"+remoteAddress+"的连接");
        }
        port=((InetSocketAddress)(ctx.channel().localAddress())).getPort();

        //注册浏览器channel
        RegistCenter registCenter = WorkSpace.getSingleInstance().getRegistCenter();
        exchangeCenter = registCenter.getExchangeCenter(port);
        if(exchangeCenter!=null){
            //放入集合
            if(!exchangeCenter.addBrowserChannel(ctx.channel())){
                //集合已经满了，不再处理更多连接，直接断开
                ctx.close();
                return;
            }
            //通知客户端建立临时连接
            exchangeCenter.createNewChannel(port);

        }
        else {
            //客户端未注册指定端口，断开连接
            ctx.close();
        }

        ctx.fireChannelRegistered();
    }

    final int MAX_DATA_LENGTH=102400;

    /**
     * 最大读取MAX_DATA_LENGTH个数据，封装成Message传递给客户端
     * @param ctx
     * @param msg
     * @throws Exception
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(clientChannel==null){
            Object o = ctx.channel().attr(AttributeKeys.CHANNEL.key).get();
            if(o!=null){
                clientChannel=(Channel)o;
            }
        }

        //发送消息至客户端
        ByteBuf m = (ByteBuf) msg;
        int readableBytes = m.readableBytes();
        while(readableBytes>0){
            int length=readableBytes<MAX_DATA_LENGTH?readableBytes:MAX_DATA_LENGTH;
            byte[] data=new byte[length];
            m.readBytes(data);
            Message message = new Message(MessageType.BROWSER_DATA,null,data);
            if(clientChannel.isActive()){
                clientChannel.writeAndFlush(message).addListener(
                        new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if(future.isSuccess()){
                                    if(Log.isDebugEnabled()){
                                        Log.debug(ctx.channel().remoteAddress()+"|"+ctx.channel().localAddress()+"发送数据至客户端成功");
                                    }
                                }
                                else {
                                    if(Log.isDebugEnabled()){
                                        Log.debug(ctx.channel().remoteAddress()+"|"+ctx.channel().localAddress()+"发送数据至客户端失败");
                                    }
                                }
                            }
                        }
                );
            }
            else {
                ctx.close();
            }
            readableBytes = m.readableBytes();
        }
        m.release();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if(Log.isDebugEnabled()){
            Log.debug("通道"+ctx.channel().localAddress()+" | "+ctx.channel().remoteAddress()+"关闭");
        }
        if(clientChannel!=null){
            clientChannel.close();
        }
        ctx.fireChannelInactive();
    }


}
